<?php
class UserPost
{
	private $db;

	public function __construct($db)
	{
		$this->db = $db;
	}

	/**
	 * 从令牌中获取用户ID
	 */
	public function getUserIdFromToken($token)
	{
		try {
			$stmt = $this->db->prepare("SELECT user_id FROM user_tokens WHERE token = ? AND expires_at > NOW()");
			$stmt->execute([$token]);
			$result = $stmt->fetch(PDO::FETCH_ASSOC);

			return $result ? $result['user_id'] : null;
		} catch (PDOException $e) {
			error_log("[UserPost Model] 令牌查询错误: " . $e->getMessage());
			throw new Exception("验证用户令牌失败");
		}
	}

	/**
	 * 根据用户ID获取帖子
	 */
	public function getPostsByUserId($userId)
	{
		try {
			$stmt = $this->db->prepare("
                SELECT p.id, p.title, p.content, p.created_at, p.views,
                       c.name AS category_name, COUNT(com.id) AS comment_count
                FROM posts p
                LEFT JOIN categories c ON p.category_id = c.id
                LEFT JOIN comments com ON p.id = com.post_id
                WHERE p.user_id = ?
                GROUP BY p.id
                ORDER BY p.created_at DESC
            ");
			$stmt->execute([$userId]);

			return $stmt->fetchAll(PDO::FETCH_ASSOC);
		} catch (PDOException $e) {
			error_log("[UserPost Model] 用户帖子查询错误: " . $e->getMessage());
			throw new Exception("获取用户帖子失败");
		}
	}
}